﻿using Newtonsoft.Json;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

using AD.Pms.Core;
using AD.Pms.Core.Jwt;
using AD.Pms.Core.ClientApi;
using AD.Pms.Core.EnumHelper;
using AD.Pms.Core.ConfigHelper;

namespace AD.Pms.Api.Authorize
{
    /// <summary>
    /// 
    /// </summary>
    public class ApiAuthorize: ActionFilterAttribute
    {
        #region prop
        /// <summary>
        /// 模块别名，可配置更改
        /// </summary>
        public string Modules { get; set; }

        /// <summary>
        /// 权限动作
        /// </summary>
        public string Methods { get; set; }

        /// <summary>
        /// 权限访问控制器参数
        /// </summary>
        private string Sign { get; set; }

        /// <summary>
        /// 是否保存日志
        /// </summary>
        public bool IsLog { get; set; } = true;

        /// <summary>
        /// 操作类型CRUD
        /// </summary>
        public LogEnum LogType { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private string ActionArguments { get; set; }

        /// <summary>
        /// 耗时
        /// </summary>
        private Stopwatch Stopwatch { get; set; }
        #endregion

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (IsLog)
            {
                ActionArguments = JsonConvert.SerializeObject(context.ActionArguments);
                Stopwatch = new Stopwatch();
                Stopwatch.Start();
            }

            var userId = "";
            // 检测是否包含'Authorization'请求头，如果不包含则直接放行
            if (context.HttpContext.Request.Headers.ContainsKey("Authorization"))
            {
                var token = context.HttpContext.Request.Headers["Authorization"];
                token = token.ToString().Substring("Bearer ".Length).Trim();

                var tm = JwtHelper.SerializeJWT(token);
                userId = tm.Uid;
            }

            // 读取权限
            var menuType = ConfigExtensions.Configuration[KeyHelper.LOGINAUTHORIZE];
            
            if (Modules.Equals("admin"))
            {
                base.OnActionExecuting(context);
            }

            if (string.IsNullOrEmpty(Modules))
            {
                ContextReturn(context, "您没有操作权限，请联系系统管理员！");
                return;
            }
            //判断是否包含权限模块
            //var menuModel = menu.Find(m => m.nameCode == Modules);
            //if (menu.All(m => m.nameCode != Modules) || menuModel.btnFun == null)
            //{
            //    ContextReturn(context, "您没有操作权限，请联系系统管理员！");
            //    return;
            //}
            //判断模块下面的权限是否包含功能
            //if (menuModel.btnFun.All(m => m.codeType != Methods))
            //{
            //    ContextReturn(context, "您没有操作权限，请联系系统管理员！");
            //    return;
            //}
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 返回API的信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="mes"></param>
        private static void ContextReturn(ActionExecutingContext context, string mes)
        {
            var res = new ApiResult<string>() { statusCode = (int)ApiEnum.Unauthorized, message = "您没有操作权限，请联系系统管理员！" };
            context.HttpContext.Response.ContentType = "application/json;charset=utf-8";
            context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(res));
            context.Result = new EmptyResult();
        }
    }
}
